const getData = () => new Promise(resolve => setTimeout(() => resolve("data"), 5000))

function* generator(){
  const data = yield getData()
  console.log('data: ', data);
  const data2 = yield getData()
  console.log('data2: ', data2);
  return 'success'
}
// 方法1
// function autoPlayGenerator(param){
//   const gen = generator()
//   function exdue(param1) {
//     const res = gen.next(param1)
//     // console.log('res====',res)
//     if (!res.done) {
//       res.value.then(r=>{
//         exdue(r)
//       })
//     } else {
//       console.log('res====---',res.value)
//     }
//   }
//   exdue(param)
// }
// autoPlayGenerator()

// 方法二
function asyncToGenerator(generatorFunc) {
  return function (){
    const gen = generatorFunc()
    return new Promise((resolve,reject)=>{
      function step(key,arg){
        let generatorResult
        try {
          generatorResult = gen[key](arg)
        } catch (error) {
          return reject(error)
        }
        const { value, done } = generatorResult
        if (done) {
          return resolve(value)
        } else {
          return Promise.resolve(value).then(val=>step('next',val),err=>step('throw',err))
        }
      }
      step('next')
    })
  }
}

const test = asyncToGenerator(generator)

test().then(res => console.log(res))